<template>
  <view class="content jlogin">
    <view class="reg" @tap="to_reg">注册</view>

    <view class="clear"></view>

    <view class="bt">
      <view class="bt01">
        登录
      </view>
      <view class="bt02">
        欢迎使用墨斗~
      </view>
    </view>
    <view class="clear"></view>

    <view class="input-group ji">
      <view class="ji_t">手机号码</view>
      <view class="input-row ">
        <m-input
          class="m-input"
          type="number"
          clearable
          focus
          v-model="account"
          maxlength="11"
          placeholder="请输入手机号码"
          @input="onKeyInput"
        ></m-input>

        <view class="j-boxs">
          <image src="../../static/img/t.png" class="j-boxsbjt"></image>

          <view class="j-boxsbj">
            <view class="j-box">
              <view
                ><text>zhangsan@zuohao.com</text>
                <image src="../../static/img/ic_login_delete.png"></image>
              </view>
            </view>
            <view class="j-box">
              <view
                ><text>zhangsan@zuohao.com</text>
                <image src="../../static/img/ic_login_delete.png"></image>
              </view>
            </view>
            <view class="j-box">
              <view
                ><text>zhangsan@zuohao.com</text>
                <image src="../../static/img/ic_login_delete.png"></image>
              </view>
            </view>
            <view class="j-box">
              <view
                ><text>zhangsan@zuohao.com</text>
                <image src="../../static/img/ic_login_delete.png"></image>
              </view>
            </view>
          </view>

          <image src="../../static/img/f.png" class="j-boxsbjf"></image>
        </view>
      </view>
      <view class="ji_t">登录密码</view>
      <view class="input-row">
        <m-input
          type="password"
          displayable
          v-model="password"
          placeholder="登录密码"
          @input="onKeyInput"
        ></m-input>
      </view>
    </view>
    <view class="btn-row" :class="{ not: !canclick }">
      <button
        type="primary"
        class="primary"
        @tap="bindLogin"
        :loading="isLoading"
      >
        登录
      </button>
    </view>
    <view class="jwj">
      <navigator url="../pwd/pwd">忘记密码</navigator>
    </view>

    <!-- 
		<view   class="jwx"  >
			<image src="../../static/img/ic_wechat.png"></image>
			<span>微信登录</span>
		</view> -->

    <!-- 	
		<button  type="primary" open-type="getUserInfo" withCredentials="true" lang="zh_CN" class="jwx"  @getuserinfo="wjeditetUserInfo">
			<image src="../../static/img/ic_wechat.png"></image>
			<span>微信登录</span>
		</button>
 -->
  </view>
</template>

<script>
import request from '@/common/request.js';
import service from '../../service.js';
let base64 = require('../../common/js/base64.js').Base64;
import { mapState, mapMutations } from 'vuex';
import mInput from '../../components/m-input.vue';

export default {
  components: {
    mInput,
  },
  data() {
    return {
      repeat_click: true,
      providerList: [],
      hasProvider: false,
      account: '',
      password: '',
      positionTop: 0,
      isDevtools: false,

      appid: '*************',
      secret: '*************************',
      code: '',
      sessionKey: '',
      openId: '',
      userInfo: {
        avatarUrl: '',
        city: '',
        country: '',
        gender: 1,
        language: '',
        nickName: '',
      },
      pageOption: {},
      canclick: false,
      isLoading: false,
    };
  },
  computed: mapState(['forcedLogin']),
  methods: {
    // 判断按钮高亮
    onKeyInput: function(event) {
      console.log(this.account, this.password);
      this.mparameterw = false;
      if (this.account != '' && this.password != '') {
        this.canclick = true;
      } else {
        this.canclick = false;
      }
    },

    // 第一授权获取用户信息 ===》按钮触发
    wjeditetUserInfo() {
      let _self = this;
      // 1.获取用户的信息
      uni.getUserInfo({
        provider: 'weixin',
        success: infoRes => {
          console.log(infoRes);
          _self.userInfo = infoRes.userInfo;
          // 2.提交数据到后台、写入数据库
          request({
            url: _self.apiServer + 'appletsUserInfo',
            data: {
              openid: _self.openId,
              avatarUrl: _self.userInfo.avatarUrl,
              city: _self.userInfo.city,
              country: _self.userInfo.country,
              gender: _self.userInfo.gender,
              language: _self.userInfo.language,
              nickName: _self.userInfo.nickName,
            },
            method: 'POST',
            success: res => {
              if (res.data.code != 200) {
                this.repeat_click = true;
                uni.showToast({
                  title: res.data.msg,
                  icon: 'none',
                });
                return false;
              }

              // 用户信息写入缓存
              this.repeat_click = true;
              uni.showToast({
                title: '登录成功',
              });

              uni.setStorageSync('access_token', res.data.data.access_token);
              uni.setStorageSync('refresh_token', res.data.data.refresh_token);
              uni.setStorageSync('user_id', res.data.data.user_id);
              uni.setStorageSync('token_type', res.data.data.token_type);
              uni.setStorageSync('expires_in', res.data.data.expires_in);

              // 获取用户信息
              request({
                url: '/ucenter/corp-user/corp/default',
                method: 'GET',

                success: res => {
                  console.log('用户信息1：', res.data.data);
                  uni.setStorageSync('user', res.data.data);
                  // 然后跳回原页面
                  if (_self.pageOption.backtype == 1) {
                    uni.redirectTo({
                      url: _self.pageOption.backpage,
                    });
                  } else {
                    uni.switchTab({
                      url: _self.pageOption.backpage,
                    });
                  }
                },
              });
            },
            fail: () => {
              this.repeat_click = true;
              uni.showToast({
                title: '用户信息操作失败',
                icon: 'none',
              });
            },
          });
        },
        fail: () => {
          this.repeat_click = true;
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none',
          });
        },
      });
      return false;
    },

    // 登录
    login() {
      let _self = this;

      // 0. 显示加载的效果
      uni.showLoading({
        title: '登录中...',
      });

      // 1. wx 获取登录用户 code
      uni.login({
        provider: 'weixin',
        success: loginRes => {
          console.log(loginRes);
          _self.code = loginRes.code;
          // 2. 将用户登录code传递到后台置换用户SessionKey、OpenId等信息
          request({
            url:
              'https://api.weixin.qq.com/sns/jscode2session?appid=' +
              _self.appid +
              '&secret=' +
              _self.secret +
              '&js_code=' +
              _self.code +
              '&grant_type=authorization_code',
            success: codeRes => {
              console.log(codeRes);
              _self.openId = codeRes.data.openid;
              _self.sessionKey = codeRes.data.session_key;
              // 3.通过 openId 判断用户是否授权
              request({
                url: _self.apiServer + 'loginApplets',
                data: {
                  openid: _self.openId,
                },
                method: 'POST',
                success: openIdRes => {
                  console.log(openIdRes);
                  // 隐藏loading
                  uni.hideLoading();
                  // 还没授权登录、请先授权然后登录
                  if (openIdRes.data.code == 1) {
                    // 提示消息、让用户授权
                    this.repeat_click = true;
                    uni.showToast({
                      title: openIdRes.data.msg,
                      icon: 'none',
                    });
                  }
                  // 已经授权了、查询到用户的数据了
                  if (openIdRes.data.success == true) {
                    // 用户信息写入缓存
                    this.repeat_click = true;
                    uni.showToast({
                      title: '登录成功',
                    });
                    uni.setStorageSync(
                      'access_token',
                      res.data.data.access_token,
                    );
                    uni.setStorageSync(
                      'refresh_token',
                      res.data.data.refresh_token,
                    );
                    uni.setStorageSync('user_id', res.data.data.user_id);
                    uni.setStorageSync('token_type', res.data.data.token_type);
                    uni.setStorageSync('expires_in', res.data.data.expires_in);

                    // 获取用户信息
                    request({
                      url: '/ucenter/user',
                      method: 'GET',

                      success: res => {
                        if (res.data.success == true) {
                          console.log('用户信息1：', res.data.data);
                          uni.setStorageSync('user', res.data.data);
                          // 然后跳回原页面
                          if (_self.pageOption.backtype == 1) {
                            uni.redirectTo({
                              url: _self.pageOption.backpage,
                            });
                          } else {
                            uni.switchTab({
                              url: _self.pageOption.backpage,
                            });
                          }
                        } else {
                          uni.navigateTo({
                            url: '../login/login',
                          });
                          console.log('qqqqqqqqq222222');
                          return false;
                        }
                      },
                    });
                  }
                },
                fail: () => {
                  this.repeat_click = true;
                  uni.showToast({
                    title: '获取授权信息失败',
                    icon: 'none',
                  });
                  return false;
                },
              });
            },
            fail: () => {
              this.repeat_click = true;
              uni.showToast({
                title: '获取 SesssionKey OpenId 失败',
                icon: 'none',
              });
              return false;
            },
          });
        },
        fail: () => {
          this.repeat_click = true;
          uni.showToast({
            title: '获取 code 失败',
            icon: 'none',
          });
          return false;
        },
      });
      return false;
    },

    to_reg() {
      uni.navigateTo({
        url: '../reg/reg',
      });
    },

    ...mapMutations(['login']),

    initPosition() {
      /**
       * 使用 absolute 定位，并且设置 bottom 值进行定位。软键盘弹出时，底部会因为窗口变化而被顶上来。
       * 反向使用 top 进行定位，可以避免此问题。
       */
      this.positionTop = uni.getSystemInfoSync().windowHeight - 100;
    },

    // 登陆
    bindLogin() {
      /**
       * 客户端对账号信息进行一些必要的校验。
       * 实际开发中，根据业务需要进行处理，这里仅做示例。
       */
      if (this.account.length < 11) {
        this.repeat_click = true;
        uni.showToast({
          icon: 'none',
          title: '手机号格式错误',
        });
        return;
      }
      if (this.password.length < 6) {
        this.repeat_click = true;
        uni.showToast({
          icon: 'none',
          title: '密码最短为6个字符',
        });
        return;
      }

      this.isLoading = true;

      //验证码正确 验证登陆   http://gateway.dev.bytes1024.cn
      request({
        url: '/ucenter/login',
        data: {
          // appId: "5efe4be4d9eff40a",
          // terminal: uni.getStorageSync("xt").platform.toUpperCase(),  base64.encode(this.password)
          // terminal: "ANDROID",
          username: this.account,
          password: this.password,
        },

        method: 'POST',
        success: openIdRes => {
          console.log(openIdRes);
          // 隐藏loading
          this.isLoading = false;

          // 已经授权了、查询到用户的数据了
          if (openIdRes.data.success == true) {
            // 用户信息写入缓存
            this.repeat_click = true;
            uni.showToast({
              title: '登录成功',
            });
            uni.setStorageSync('access_token', openIdRes.data.data);
            var ac = uni.getStorageSync('jkcs');

            if (uni.getStorageSync('access_token')) {
              ac.token = uni.getStorageSync('access_token');
            }

            uni.setStorageSync('jkcs', ac);

            console.log(uni.getStorageSync('jkcs'));

            // uni.setStorageSync('refresh_token', openIdRes.data.data.refresh_token);
            // uni.setStorageSync('user_id', openIdRes.data.data.user_id);
            // uni.setStorageSync('token_type', openIdRes.data.data.token_type);
            // uni.setStorageSync('expires_in', openIdRes.data.data.expires_in);

            var that = this;

            // 获取用户信息
            request({
              url: '/ucenter/corp-user/corp/default',
              method: 'GET',

              success: res => {
                console.log('用户信息1123213：', res.data.data);
                uni.setStorageSync('user', res.data.data);
                uni.reLaunch({
                  url: '../main/main',
                });
                // that.toMain(openIdRes.data.data.access_token);
                // 然后跳回原页面
                // if (_self.pageOption.backtype == 1) {
                // 	uni.redirectTo({
                // 		url: _self.pageOption.backpage
                // 	})
                // } else {
                // 	uni.switchTab({
                // 		url: _self.pageOption.backpage
                // 	})
                // }
              },
            });

            // 然后跳回原页面
            // if (this.pageOption.backtype == 1) {
            // 	uni.redirectTo({
            // 		url: this.pageOption.backpage
            // 	})
            // } else {
            // 	uni.switchTab({
            // 		url: this.pageOption.backpage
            // 	})
            // }
          } else {
            this.repeat_click = true;
            uni.showToast({
              title: openIdRes.data.msg,
              icon: 'none',
            });
          }
        },
      });
    },

    getUserInfo({ detail }) {
      if (detail.userInfo) {
        this.toMain(detail.userInfo.nickName);
      } else {
        this.repeat_click = true;
        uni.showToast({
          icon: 'none',
          title: '登陆失败',
        });
      }
    },
    toMain(userName) {
      console.log(111);
      this.login(userName);
      uni.reLaunch({
        url: '../main/main',
      });
      /**
       * 强制登录时使用reLaunch方式跳转过来
       * 返回首页也使用reLaunch方式
       */
      // if (this.forcedLogin) {
      // 	uni.reLaunch({
      // 		url: '../main/main',
      // 	});
      // } else {
      // 	uni.navigateBack();
      // }
    },
  },

  onLoad(options) {
    // 接收跳转的参数
    this.pageOption = options;

    if (uni.getStorageSync('lsphone')) {
      console.log('aaaa', uni.getStorageSync('lsphone'));
      this.account = uni.getStorageSync('lsphone');
    }
    //默认加载
    this.login();
  },

  onReady() {
    this.initPosition();
    // this.initProvider();
    // #ifdef MP-WEIXIN
    this.isDevtools = uni.getSystemInfoSync().platform === 'devtools';
    // #endif
  },
};
</script>

<style>
.j-boxsbj {
  width: 97%;
  padding: 0 1.5%;
  height: auto;
  display: block;
  float: left;
  position: relative;
  background: url(../../static/img/c.png);
  background-repeat: repeat-y;
  background-size: 100% auto;
}

.j-boxsbjt {
  width: 100%;
  height: 33rpx;
  display: block;
  float: left;
}

.j-boxsbjf {
  width: 100%;
  height: 23rpx;
  display: block;
  float: left;
}

.j-boxs {
  width: 550rpx;
  height: auto;
  display: none;
  float: left;
  margin: 0;
  position: absolute;
  left: 35rpx;
  top: 60rpx;
  z-index: 99999;
  border-radius: 8px;
}

.j-box {
  width: 100%;
  height: 90rpx;
  display: block;
  line-height: 90rpx;
  float: left;
}

.j-box view {
  width: 90%;
  height: 90rpx;
  display: block;
  line-height: 90rpx;
  float: left;
  margin: 0 5%;
  border-bottom: 1px solid #dddddd;
}

.j-box text {
  width: 80%;
  height: 90rpx;
  display: block;
  line-height: 90rpx;
  float: left;
  font-size: 32rpx;
  color: #000000;
}

.j-box image {
  width: 36rpx;
  height: 36rpx;
  display: block;
  margin: 27rpx 30rpx 0 0;
  float: right;
}

.j-box:active {
  background: #eeeeee;
}

.reg {
  width: auto;
  height: auto;
  font-size: 32rpx;
  color: #256aff;
  float: right;
  display: block;
  margin: 100rpx 50rpx 0 0;
  padding: 10rpx;
  text-align: right;
}

.bt {
  width: auto;
  height: auto;
  float: left;
  display: block;
  margin: 60rpx 0rpx 0 60rpx;
}

.bt01 {
  width: auto;
  height: auto;
  display: block;
  font-size: 68rpx;
  color: #000000;
  margin: 0rpx 0rpx 40rpx 0rpx;
}

.bt02 {
  width: auto;
  height: auto;
  display: block;
  font-size: 36rpx;
  color: #000000;
}

.ji {
  width: 630rpx;
  height: auto;
  display: block;
  float: left;
  margin: 26rpx 60rpx 0rpx;
}

.ji_t {
  width: 100%;
  height: auto;
  display: block;
  float: left;
  font-size: 20rpx;
  color: #999999;
  margin: 0 0 10rpx 0;
  visibility: hidden;
}

.ji .input-row {
  width: 100%;
  height: 60rpx;
  display: block;
  float: left;
  border-bottom: 1px solid #dddddd;
  margin: 0 0 40rpx 0;
  position: relative;
}

.ji .m-input-input {
  width: 90%;
  height: 40rpx;
  display: block;
  float: left;
  margin: 0 0 40rpx 0;
  font-size: 32rpx;
  color: #000000;
}

.ji .m-input-view {
  width: 100%;
  height: auto;
  display: block;
  float: left;
}

.jwx {
  width: 630rpx;
  height: auto;
  display: block;
  float: left;
  position: fixed;
  left: 60rpx;
  bottom: 90rpx;
  background: #ffffff;
  border: 1px solid #dddddd;
  box-sizing: border-box;
  border-radius: 8rpx;
  text-align: center;
  font-size: 36rpx;
  color: #000000;
  line-height: 56rpx;
  height: 56rpx;
  padding: 19rpx 0;
  box-sizing: content-box;
  margin: 0;
}

.jwx image {
  width: 56rpx;
  height: 56rpx;
  float: none;
  display: inline-block;
  margin: 0 10rpx -15rpx 0;
}

.jwx span {
  width: auto;
  height: 56rpx;
  float: none;
  display: inline-block;
  line-height: 56rpx;
}

.jwx:active {
  background: #f5f5f5;
  border: 1px solid #dddddd;
  color: #000000;
}

.jlogin .not uni-button {
  opacity: 0.5;
}
</style>
